package com.learn.netty_learn;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import com.learn.netty_learn.utils.ByteBufferUtil;

import lombok.extern.slf4j.Slf4j;
/*
 * 此处代码的问题：
 * 1. sc.register 会被 Worker中的selector.select 阻塞，导致无法注册
 */
@Slf4j
public class P1_44_MultiThreadServer {
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        int port = 8080;
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector boss = Selector.open();
        SelectionKey bossKey = ssc.register(boss,0,null);
        bossKey.interestOps(SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(port));
        Worker worker = new Worker("worker-0");
        while(true){
            boss.select(); // 阻塞方法
            System.out.println("boss selected");
            Iterator<SelectionKey> iterator = boss.selectedKeys().iterator();
            while(iterator.hasNext()){
                SelectionKey key = iterator.next();
                iterator.remove();
                if(key.isAcceptable()){
                    // 连接建立了
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    log.info("connected...{}",sc.getRemoteAddress());
                    //2 关联selector
                    log.info("before register...{}",sc.getRemoteAddress());
                    worker.register(sc);
                    log.info("after register...{}",sc.getRemoteAddress());  
                }
            }
        }

    }
    static class Worker implements Runnable{
        private Thread thread;
        private Selector selector;
        private String name;
        private volatile boolean start = false;
        public Worker(String name){
            this.name = name;
        }

        public void register(SocketChannel sc) throws IOException {
            if(!this.start){
                this.selector = Selector.open();
                this.thread = new Thread(this,name);
                this.thread.start();
                this.start = true;
            }
            this.selector.wakeup();
            sc.register(this.selector, SelectionKey.OP_READ, null);
        }
        
        @Override
        public void run(){
            while(true){
                try{
                    this.selector.select(); // 阻塞方法
                    Iterator<SelectionKey> iterator = this.selector.selectedKeys().iterator();
                    while(iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if(key.isReadable()){
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel channel = (SocketChannel) key.channel();
                            log.info(name+" read...{}",channel.getRemoteAddress());
                            channel.read(buffer);
                            buffer.flip();
                            ByteBufferUtil.debugAll(buffer);
                        }
                    }
                }catch(IOException e){
                    e.printStackTrace();
                }
            }
        }
        
    }
    
}
